<template>
  <view>
    <h2>自动触发</h2>
    <view v-if="state.loading">loading</view>
    <view v-else-if="state.error">error</view>
    <view v-else>{{state.data}}</view>
    <view>------------------------</view>
    <h2>手动触发</h2>
    <view v-if="manualState.loading">loading</view>
    <view v-else-if="manualState.error">error</view>
    <view v-else>{{manualState.data}}</view>
    <button @click="manualState.run()">加载数据</button>
    <view>------------------------</view>
    <h2>局部刷新</h2>
    <view v-if="hotState.loading">loading</view>
    <view v-else-if="hotState.error">error</view>
    <view v-else>
      {{hotState.data}}
      <text v-if="hotState.isRefresh">局部刷新中</text>
    </view>
    <button @click="hotState.reFresh()">局部刷新</button>
    <view>------------------------</view>
    <h2>加载更多</h2>
    <view v-if="listState.loading">loading</view>
    <view v-else-if="listState.error">error</view>
    <view v-for="item in listState.data">{{item.name}}</view>
    <view v-if="listState.loadingMore">加载中</view>
    <view v-if="!listState.isThereMore">没有更多了</view>
    <button @click="loadMore">加载更多</button>
    <view>------------------------</view>
  </view>
</template>

<script>
import {useRequest} from '@/utils/useRequest'

//模拟普通接口
function commonApi() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const time=new Date()
      resolve({
        code: 0,
        result: `${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`,
        message: 'success'
      })
    }, 1000)
  })
}
//模拟列表
function listApi(data){
  return new　Promise((resolve, reject) => {
    setTimeout(()=>{
      resolve({
        code:0,
        message:"",
        result:{
          total:12,
          records:[
            {
              name:'tang'+data,id:1
            },
            {
              name:'tang',id:2
            },
            {
              name:'tang',id:3
            },
            {
              name:'tang',id:1
            },
          ]
        }
      })
    },1000)
  })
}

//模拟调用接口
async function getCommonData() {
  const e = await commonApi()
  if (e.code === 0) return e.result
  else throw e.message
}
//模拟调用接口
async function getListData(data) {
  const e = await listApi(data)
  if (e.code === 0) return e.result
  else throw e.message
}
export default {
  created() {
    //如果参数依赖其他的data，则只能在data初始化之后操作
    //pageNum没啥用 只是告诉下 带参数怎么使用
    this.listState=useRequest(()=>getListData(this.pageNum),{loadMoreMod: true})
  },
  data() {
    return {
      state: useRequest(getCommonData),
      manualState:useRequest(getCommonData,{manual:true}),
      hotState:useRequest(getCommonData),
      listState:"",
      pageNum:1,
    }
  },
  methods: {
    loadMore(){
      this.pageNum++
      this.listState.loadMore()
    },
  }
}
</script>

<style>

</style>
